package com.leyou.web;

import com.leyou.common.enums.LyEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.entity.UserInfo;
import com.leyou.pojo.JwtProperties;
import com.leyou.service.AutoService;
import com.leyou.user.pojo.User;
import com.leyou.utils.JwtUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.text.html.parser.Entity;

@RestController
@EnableConfigurationProperties(JwtProperties.class)
public class AuthController {
    @Autowired
    private AutoService autoService;

    @Autowired
    private JwtProperties jwtProperties;

    /**
     *
     * @param username
     * @param password
     * @return
     */
    @PostMapping("login")
    public ResponseEntity<Void> login(@RequestParam("username") String username,
                                      @RequestParam("password") String password, HttpServletResponse response,HttpServletRequest request){
        String token = autoService.login(username,password);
        CookieUtils.setCookie(request,response,"token",token);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    /**
     * 验证token
     * @param token
     * @return
     */
    @GetMapping("verify")
    public ResponseEntity<UserInfo> verify(@CookieValue(value = "token",required = false)String token,HttpServletRequest request,HttpServletResponse response){
        if(StringUtils.isBlank(token)){
            throw  new LyException(LyEnum.NO_TOMEN);
        }
        try {
            //解析token
            UserInfo userInfo = JwtUtils.getUserInfo(jwtProperties.getPublicKey(), token);
            JwtUtils.generateToken(userInfo, jwtProperties.getPrivateKey(), jwtProperties.getExpire());
            CookieUtils.setCookie(request, response, "token", token);
            return ResponseEntity.ok(userInfo);
        }catch (Exception e){

        }
        return ResponseEntity.status(500).build();
    }
}
